package com.bwie.controller;

import com.bwie.config.ParkInfo;
import com.bwie.pojo.Park;
import com.bwie.service.ParkService;
import com.bwie.utils.OSSFileUtil;
import com.bwie.utils.R;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.query.HighlightQuery;
import org.springframework.data.elasticsearch.core.query.HighlightQueryBuilder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @Auther:${涛}
 * @Date:2024/9/4 10:00
 * @Description: ParkController
 * @Version 1.0.0
 */
@RestController
@RequestMapping("/park")
public class ParkController {

    @Autowired
    private ParkService parkService;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    //创建ES表
    @PostMapping("/save")
    public R save() {
        //对应的表数据ParkInfo
        IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(ParkInfo.class);
        //查询是否创建
        boolean exists = indexOperations.exists();
        if (exists) {
            //删除创建
            indexOperations.delete();
        }
        //创建
        indexOperations.create();
        //查询出要赋值的数据
        Document mapping = indexOperations.createMapping();
        //赋值
        indexOperations.putMapping(mapping);
        return R.OK("ES创建成功");
    }

    //图片上传
    @PostMapping("/file")
    public R file(MultipartFile file) throws IOException {
        OSSFileUtil ossFileUtil = new OSSFileUtil();
        String url = ossFileUtil.uploadFile(file);
        return R.OK(url);
    }


    /*
    4.1 先全量将球场数据同步到ES中
4.2 后定时增量同步到ElasticSearch中 ，每3分钟同步一次
4.3 球场名称进行模糊查询，时间范围查询，分页、可以根据输入页跳转，
4.4 高亮查询、完成球场的高亮查询和展示。
4.5 排序：优先审核中状态，再展示审核不通过，最后展示审核通过，状态相同按照创建时间进行倒序展示。
     */

    @PostMapping("/parkList")
    public R parkList(@RequestBody Park park) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //查询所用
        boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        //判断是否有数据，选择要查询的数据
        if (!StringUtils.isEmpty(park.getName())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("name", park.getName()));
        }

        //根据时间范围查询出数据
        if (!StringUtils.isEmpty(park.getBegTime()) && !StringUtils.isEmpty(park.getEndTime())) {
            boolQueryBuilder.must(QueryBuilders.rangeQuery("time").format("yyyy-MM-dd HH:mm:ss").timeZone("GMT").gt(park.getBegTime()).lt(park.getEndTime()));
        }

        //分页
        int pageNum = 0;
        if (park.getPageNum() > 0) {
            pageNum = park.getPageNum() - 1;
        }
        PageRequest request = PageRequest.of(pageNum, park.getPageSize());

        //高亮查询出数据改变颜色
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name").preTags("<font color=red>").postTags("</font>");

        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();

        nativeSearchQueryBuilder.withPageable(request).withHighlightBuilder(highlightBuilder).withQuery(boolQueryBuilder);


        SearchHits<ParkInfo> searchHits = elasticsearchRestTemplate.search(nativeSearchQueryBuilder.build(), ParkInfo.class);

        long total = searchHits.getTotalHits();
        ArrayList<ParkInfo> parkArrayList = new ArrayList<>();
        for (SearchHit<ParkInfo> searchHit : searchHits.getSearchHits()) {
            ParkInfo content = searchHit.getContent();
            List<String> name = searchHit.getHighlightField("name");
            if (name != null && name.size() > 0) {
                String s = name.get(0);
                content.setName(s);
            }
            parkArrayList.add(content);
        }

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("total", total);
        hashMap.put("pageNum", pageNum + 1);
        hashMap.put("pageSize", park.getPageSize());
        hashMap.put("parkArrayList", parkArrayList);
        return R.OK(hashMap);
    }

    @PostMapping("/parkAdd")
    public R parkAdd(@RequestBody Park park) {
        parkService.parkAdd(park);
        return R.OK("添加成功");
    }


}


